import { PrismaClient } from '@/generated/prisma';
import { logger } from '@utils/logger';
import { LogBizId, LogOperation } from '@decorators/logs.decorators';
import { Container } from 'typedi';

export const prisma: PrismaClient = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
    {
      emit: 'event',
      level: 'error',
    },
    {
      emit: 'event',
      level: 'info',
    },
    {
      emit: 'event',
      level: 'warn',
    },
  ],
});

// 监听查询日志
prisma.$on('query', e => {
  logger.debug('Query: ' + e.query);
  logger.debug('Params: ' + e.params);
  logger.debug('Duration: ' + e.duration + 'ms');
});

// 监听错误日志
prisma.$on('error', e => {
  logger.error('Prisma Error: ' + e.message);
});

// 监听信息日志
prisma.$on('info', e => {
  logger.info('Prisma Info: ' + e.message);
});

// 监听警告日志
prisma.$on('warn', e => {
  logger.warn('Prisma Warning: ' + e.message);
});

// 测试数据库连接
prisma
  .$connect()
  .then(async () => {
    logger.info('✅ Prisma 数据库连接成功');

    await prisma.sysAuditLog.create({
      data: {
        bizType: 'system',
        bizId: LogBizId.SYS_START,
        operation: LogOperation.SYS_START,
        operatorId: 0,
        operatorName: 'system',
        content: { pid: process.pid, version: process.env.npm_package_version },
        requestId: 'boot_' + Date.now(),
        ip: '127.0.0.1',
        ua: 'Node/' + process.version,
      },
    });
  })
  .catch(error => {
    logger.error('❌ Prisma 数据库连接错误:', error);
  });

const gracefulShutdown = async (signal: string) => {
  try {
    await prisma.sysAuditLog.create({
      data: {
        bizType: 'system',
        bizId: LogBizId.SYS_SHUTDOWN,
        operation: LogOperation.SYS_SHUTDOWN,
        operatorId: 0,
        operatorName: 'system',
        content: { signal, pid: process.pid, version: process.env.npm_package_version },
        requestId: 'shutdown_' + Date.now(),
        ip: '127.0.0.1',
        ua: 'Node/' + process.version,
      },
    });
    await prisma.$disconnect();
    logger.info('Prisma connection closed');
  } catch (e) {
    logger.error('Graceful shutdown error:', e);
  }
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

Container.set('PRISMA_CLIENT', prisma); // 用类本身当 token
